//
//  XMChessBoardView.m
//  TestView
//
//  Created by lk@wxm on 2024/12/4.
//

#import "XMChessBoardView.h"

@implementation XMChessBoardView

- (instancetype)initWithBoardSize:(NSInteger)size andFrame:(CGRect)frame {
    self = [super init];
    if (self) {
        if (size <= 0) {
            size = 8;  // 默认棋盘大小为8x8
        }
        self.boardSize = size;
        self.boardState = [NSMutableArray arrayWithCapacity:size];
        self.currentPlayer = 1;  // 初始玩家为黑子
        self.frame = frame;

        // 初始化棋盘状态
        for (NSInteger i = 0; i < size; i++) {
            NSMutableArray *row = [NSMutableArray arrayWithCapacity:size];
            for (NSInteger j = 0; j < size; j++) {
                [row addObject:@(0)];  // 初始化为空
            }
            [self.boardState addObject:row];
        }

        // 创建UICollectionView
        [self setupCollectionView];

        // 初始化棋盘中心棋子
        [self setupInitialPieces];
    }
    return self;
}

- (void)setupCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(self.frame.size.width / self.boardSize, self.frame.size.width / self.boardSize);
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;

    self.collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor greenColor];

    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
    [self addSubview:self.collectionView];
}

- (void)setupInitialPieces {
    NSInteger mid = self.boardSize / 2;
    self.boardState[mid - 1][mid - 1] = @(1); // 黑子
    self.boardState[mid - 1][mid] = @(2);     // 白子
    self.boardState[mid][mid - 1] = @(2);     // 白子
    self.boardState[mid][mid] = @(1);         // 黑子
}

#pragma mark - UICollectionView DataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.boardSize * self.boardSize;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    NSInteger row = indexPath.item / self.boardSize;
    NSInteger col = indexPath.item % self.boardSize;

    cell.contentView.backgroundColor = (row + col) % 2 == 0 ? [UIColor greenColor] : [UIColor greenColor];

    for (UIView *subview in cell.contentView.subviews) {
        [subview removeFromSuperview];
    }

    NSInteger piece = [self.boardState[row][col] integerValue];
    if (piece == 1) {
        UIView *blackPiece = [[UIView alloc] initWithFrame:CGRectMake(5, 5, cell.frame.size.width - 10, cell.frame.size.height - 10)];
        blackPiece.layer.cornerRadius = (cell.frame.size.width - 10) / 2;
        blackPiece.backgroundColor = [UIColor blackColor];
        [cell.contentView addSubview:blackPiece];
    } else if (piece == 2) {
        UIView *whitePiece = [[UIView alloc] initWithFrame:CGRectMake(5, 5, cell.frame.size.width - 10, cell.frame.size.height - 10)];
        whitePiece.layer.cornerRadius = (cell.frame.size.width - 10) / 2;
        whitePiece.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:whitePiece];
    }

    cell.layer.borderColor = [UIColor lightGrayColor].CGColor;
    cell.layer.borderWidth = 0.5;

    return cell;
}

#pragma mark - UICollectionView Delegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.item / self.boardSize;
    NSInteger col = indexPath.item % self.boardSize;

    if ([self.boardState[row][col] integerValue] != 0) {
        return;  // 不能放置在已有棋子的位置
    }

    NSInteger opponentPlayer = self.currentPlayer == 1 ? 2 : 1;
    NSMutableArray<NSIndexPath *> *affectedIndexes = [NSMutableArray array];

    if ([self placePieceAtRow:row col:col player:self.currentPlayer opponent:opponentPlayer affectedIndexes:affectedIndexes]) {
        self.boardState[row][col] = @(self.currentPlayer);
        [affectedIndexes addObject:indexPath];
        [collectionView reloadItemsAtIndexPaths:affectedIndexes];
        self.currentPlayer = opponentPlayer;  // 切换玩家
    }
}

- (BOOL)placePieceAtRow:(NSInteger)row col:(NSInteger)col player:(NSInteger)player opponent:(NSInteger)opponent affectedIndexes:(NSMutableArray<NSIndexPath *> *)affectedIndexes {
    BOOL hasFlipped = NO;
    //黑白棋的8个方向，分别对应：上、下、左、右。左上、右上、左下、右下。
    NSArray<NSArray<NSNumber *> *> *directions = @[
        @[@(-1), @0], @[@(1), @0], @[@0, @(-1)], @[@0, @(1)],
        @[@(-1), @(-1)], @[@(-1), @(1)], @[@(1), @(-1)], @[@(1), @(1)]
    ];
    //遍历每个方向
    for (NSArray<NSNumber *> *direction in directions) {
        NSInteger deltaRow = [direction[0] integerValue];
        NSInteger deltaCol = [direction[1] integerValue];
        NSMutableArray<NSArray<NSNumber *> *> *toFlip = [NSMutableArray array];

        NSInteger currentRow = row + deltaRow;
        NSInteger currentCol = col + deltaCol;
        //落子的合法性检查，依赖于棋盘某个方向上是否存在连续的对手棋子，并且最终有一个己方棋子“封住”。
        //如果没有找到可以翻转的棋子路径，hasFlipped 将保持为 NO，函数返回 NO。
        BOOL isValid =[self isValidRow:currentRow col:currentCol];
        while (isValid &&
               [self.boardState[currentRow][currentCol] integerValue] == opponent) {
            //将对手的子加入待反转数组
            [toFlip addObject:@[@(currentRow), @(currentCol)]];
            currentRow += deltaRow;
            currentCol += deltaCol;
        }
       
        if ( isValid&&
            [self.boardState[currentRow][currentCol] integerValue] == player) {
            hasFlipped = YES;
            //反转
            for (NSArray<NSNumber *> *position in toFlip) {
                NSInteger flipRow = [position[0] integerValue];
                NSInteger flipCol = [position[1] integerValue];
                self.boardState[flipRow][flipCol] = @(player);
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:(flipRow * self.boardSize + flipCol) inSection:0];
                [affectedIndexes addObject:indexPath];
            }
            if ([affectedIndexes count]==0){
                hasFlipped = NO;
            }
        }
    }
    return hasFlipped;
}
//在棋盘内
- (BOOL)isValidRow:(NSInteger)row col:(NSInteger)col {
    return row >= 0 && row < self.boardSize && col >= 0 && col < self.boardSize;
}

@end
